package com.zc.mychart.chart;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CandleDataSet;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.BarLineChartTouchListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.MPPointD;
import com.zc.mychart.R;
import com.zc.mychart.model.BOLLEntrys;
import com.zc.mychart.model.EMAEntrys;
import com.zc.mychart.model.EntryData;
import com.zc.mychart.model.GoldTransitionEntry;
import com.zc.mychart.model.KTrainRect;
import com.zc.mychart.model.KViewMode;
import com.zc.mychart.model.LineType;
import com.zc.mychart.model.MAEntrys;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/2/24 0024.
 */

public class MyKChart extends CombinedChart {
    private Context mContext;
    private MarkerViewX markerViewX;
    private KMarkerViewLeftY markerViewLeftY;
    private KMarkerViewRightY markerViewRightY;
    private List<CandleEntry> mCandleEntries = new ArrayList<>();
    private final float MIN_VISIBLE_COUNT = 20f;
    private float xVisibleRange = 40f;
    private List<CandleEntry> candleEntryList = new ArrayList<>();
    private LineType currentType = LineType.SMA;
    private MyBarChart myBarChart;
    private int valueX = -1;

    private int bgColor;
    private int lineColor;
    private int textColor;
    private int contentColor;
    private int bgMarker;
    private int markerTextColor;
    private int bgCandleMarker;

    public MyKChart(Context context) {
        super(context);
        mContext = context;
    }

    public MyKChart(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    public MyKChart(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
    }

    @Override
    protected void init() {
        super.init();
        mXAxisRenderer = new MyXAxisRender(mViewPortHandler, mXAxis, mLeftAxisTransformer);
        mAxisRendererLeft = new MyYAxisRender(mViewPortHandler, mAxisLeft, mLeftAxisTransformer);
        mChartTouchListener = new MyBarLineChartTouchListener(this, mViewPortHandler.getMatrixTouch(), 3f);
        mLegendRenderer = new MyLegendRenderer(mViewPortHandler, mLegend);
    }

    public void setLightBg() {
        lineColor = ContextCompat.getColor(mContext, R.color.mychart_gray_k_line);
        bgColor = ContextCompat.getColor(mContext, R.color.mychart_white_background);
        textColor = ContextCompat.getColor(mContext, R.color.mychart_text_gray_01);
        contentColor = ContextCompat.getColor(mContext, R.color.mychart_black);
        bgMarker = R.drawable.k_marker_border_gray;
        markerTextColor = ContextCompat.getColor(mContext, R.color.mychart_black);
        bgCandleMarker = ContextCompat.getColor(mContext, R.color.mychart_gray_bg_time_type);
        setColors();
    }

    public void setDarkBg(KViewMode mKlineMode) {
        lineColor = ContextCompat.getColor(mContext, R.color.mychart_k_line);
        bgColor = ContextCompat.getColor(mContext, R.color.mychart_background);
        textColor = ContextCompat.getColor(mContext, R.color.mychart_white);
        contentColor = ContextCompat.getColor(mContext, R.color.mychart_white);
        bgMarker = R.drawable.k_marker_border;
        markerTextColor = ContextCompat.getColor(mContext, R.color.mychart_text_gray);
        bgCandleMarker = ContextCompat.getColor(mContext, R.color.mychart_bg_time_type);
        setColors();
    }

    private void setColors() {
        setBackgroundColor(bgColor);
        setBorderColor(lineColor);
        mXAxis.setGridColor(lineColor);
        mAxisLeft.setGridColor(lineColor);
        mXAxis.setTextColor(textColor);
        mLegend.setTextColor(textColor);
        mAxisLeft.setTextColor(textColor);
        markerViewX.setMarkerBg(bgMarker, markerTextColor);
        markerViewLeftY.setMarkerBg(bgMarker, markerTextColor);
        markerViewRightY.setMarkerBg(bgCandleMarker);
        markerViewRightY.setTitleColor(textColor);
        markerViewRightY.setContentColor(contentColor);
    }

    public void initView() {
        lineColor = ContextCompat.getColor(mContext, R.color.mychart_k_line);
        bgColor = ContextCompat.getColor(mContext, R.color.mychart_background);
        textColor = ContextCompat.getColor(mContext, R.color.mychart_white);
        bgMarker = R.drawable.k_marker_border;
        markerTextColor = ContextCompat.getColor(mContext, R.color.mychart_text_gray);
        bgCandleMarker = ContextCompat.getColor(mContext, R.color.mychart_bg_time_type);

        setMinOffset(0f);
        setDrawBorders(true);
        setBorderColor(lineColor);
        setBorderWidth(1f);
        setPinchZoom(true);
        setScaleYEnabled(false);
        setAutoScaleMinMaxEnabled(true);
        setNoDataText("");
        getDescription().setEnabled(false);

        setBackgroundColor(bgColor);
        setDrawOrder(new DrawOrder[]{DrawOrder.CANDLE, DrawOrder.LINE, DrawOrder.SCATTER});
        setDragDecelerationFrictionCoef(0.95f);
        setDoubleTapToZoomEnabled(false);
//        setPinchZoom(false);
//        setDragEnabled(false);
//        setScaleXEnabled(false);
//        setScaleYEnabled(false);
        markerViewX = new MarkerViewX(mContext, R.layout.view_marker);
        markerViewLeftY = new KMarkerViewLeftY(mContext, R.layout.view_marker);
        markerViewRightY = new KMarkerViewRightY(mContext, R.layout.k_view_marker);
        markerViewX.setChartView(this);
        markerViewLeftY.setChartView(this);
        markerViewRightY.setChartView(this);
        markerViewX.setMarkerBg(bgMarker, markerTextColor);
        markerViewLeftY.setMarkerBg(bgMarker, markerTextColor);
        markerViewRightY.setMarkerBg(bgCandleMarker);

        mXAxis.setDrawAxisLine(false);
        mXAxis.setDrawGridLines(true);
        mXAxis.setGridColor(lineColor);
        mXAxis.setYOffset(10f);
        mXAxis.setLabelCount(5);
        mXAxis.setAvoidFirstLastClipping(true);
        mXAxis.setTextColor(textColor);
        mXAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        mXAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                try {
                    int i = (int) value;
                    if (i > -1 && i < mCandleEntries.size()) {
                        EntryData data = (EntryData) mCandleEntries.get((int) value).getData();
                        if (data != null) {
                            return data.time;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return "";
            }

        });

        mAxisLeft.setDrawAxisLine(false);
        mAxisLeft.setDrawGridLines(true);
        mAxisLeft.setGridColor(lineColor);
        mAxisLeft.setTextColor(textColor);
        mAxisLeft.setLabelCount(5);
        mAxisLeft.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
        mAxisRight.setEnabled(false);

        mLegend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        mLegend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        mLegend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        mLegend.setDrawInside(true);
        mLegend.setForm(Legend.LegendForm.LINE);
        mLegend.setTextColor(textColor);
        mLegend.setXOffset(50f);

        computeScroll();
    }

    public void setMyBarChart(MyBarChart barChart) {
        this.myBarChart = barChart;
        setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                valueX = Math.round(h.getX());
                updateDataLabel(valueX);
                myBarChart.highlightValues(new Highlight[]{h});
            }

            @Override
            public void onNothingSelected() {
                valueX = -1;
                updateDataLabel(valueX);
                myBarChart.highlightValues(new Highlight[]{null});
            }
        });
    }


    public synchronized void setCandleData(LineType type, List<CandleEntry> candleEntryList,boolean isReset) {
        //CandleDataSet为空会引发脚标越界异常
        if (candleEntryList != null && candleEntryList.size() > 0) {
            this.candleEntryList = candleEntryList;
            if(isReset){
                float xRange = getVisibleXRange();
                if (xRange != 0) {
                    xVisibleRange = xRange;
                }
                resetTracking();
                CandleData candleData;
                if (LineType.HJGD == type) {
                    GoldTransitionEntry goldTransitionEntry = new GoldTransitionEntry(candleEntryList);
                    candleData = generateCandleDataDK(goldTransitionEntry.getTransformList());
                } else {
                    candleData = generateCandleData(candleEntryList);
                }
                CombinedData combinedData = new CombinedData();
                combinedData.setData(candleData);
                mXAxis.setAxisMinimum(combinedData.getXMin() - 0.5f);
                mXAxis.setAxisMaximum(combinedData.getXMax() + 0.5f);
                setData(combinedData);
                calculateScale();
                setLineData(type, candleEntryList, isReset);
            }else{
                invalidate();
            }
        } else {
            clear();
        }
    }

    public void setLineData(LineType type, List<CandleEntry> candleEntryList) {
        setLineData(type, candleEntryList, false);
    }

    private List<CandleEntry> mCandleEntryList;

    public List<CandleEntry> getCandleEntryList() {
        return mCandleEntryList;
    }


    String ma5Label = "";
    String ma10Label = "";
    String ma20Label = "";
    String emaLabel = "";
    String upsLabel = "";
    String dnsLabel = "";

    private void setLineData(LineType type, List<CandleEntry> candleEntryList, boolean isReset) {
        currentType = type;
        if (candleEntryList != null && candleEntryList.size() > 0) {
            mCandleEntryList = candleEntryList;
            LineData lineData = new LineData();
            CombinedData combinedData = getCombinedData();
            ScatterData scatterData = new ScatterData();

            if (LineType.HJGD != type) {
                combinedData.getCandleData().clearValues();
                CandleData candleData = generateCandleData(candleEntryList);
                combinedData.setData(candleData);
                combinedData.setData(scatterData);
            }

            switch (type) {
                case SMA:
                    MAEntrys maEntries = new MAEntrys(candleEntryList);
                    if (maEntries.getMA5s().size() > 0) {
                        ma5Label = "SMA5=" + maEntries.getMA5s().get(maEntries.getMA5s().size() - 1).getY();
                    }
                    if (maEntries.getMA10s().size() > 0) {
                        ma10Label = "SMA10=" + maEntries.getMA10s().get(maEntries.getMA10s().size() - 1).getY();
                    }
                    if (maEntries.getMA20s().size() > 0) {
                        ma20Label = "SMA20=" + maEntries.getMA20s().get(maEntries.getMA20s().size() - 1).getY();
                    }
                    LineDataSet ma5DataSet = generateLineDataSet(maEntries.getMA5s(), ContextCompat.getColor(mContext, R.color.mychart_k_line_ma5), ma5Label);
                    LineDataSet ma10DataSet = generateLineDataSet(maEntries.getMA10s(), ContextCompat.getColor(mContext, R.color.mychart_k_line_ma10), ma10Label);
                    LineDataSet ma20DataSet = generateLineDataSet(maEntries.getMA20s(), ContextCompat.getColor(mContext, R.color.mychart_k_line_ma20), ma20Label);
                    lineData.addDataSet(ma5DataSet);
                    lineData.addDataSet(ma10DataSet);
                    lineData.addDataSet(ma20DataSet);
                    break;
                case EMA:
                    EMAEntrys emaEntrys = new EMAEntrys(candleEntryList);
                    if (emaEntrys.getEMAs().size() > 0) {
                        emaLabel = "EMA=" + emaEntrys.getEMAs().get(emaEntrys.getEMAs().size() - 1).getY();
                    }
                    LineDataSet ema20DataSet = generateLineDataSet(emaEntrys.getEMAs(), ContextCompat.getColor(mContext, R.color.mychart_k_line_ema), emaLabel);
                    lineData.addDataSet(ema20DataSet);
                    break;
                case BOLL:
                    BOLLEntrys bollEntrys = new BOLLEntrys(candleEntryList);
                    //String mbsLable = "MB=" + bollEntrys.getMBs().get(bollEntrys.getMBs().size() - 1).getY();
                    if (bollEntrys.getUPs().size() > 0) {
                        upsLabel = "UP=" + bollEntrys.getUPs().get(bollEntrys.getUPs().size() - 1).getY();
                    }
                    if (bollEntrys.getDNs().size() > 0) {
                        dnsLabel = "DN=" + bollEntrys.getDNs().get(bollEntrys.getDNs().size() - 1).getY();
                    }
                    LineDataSet upDataSet = generateLineDataSet(bollEntrys.getUPs(), ContextCompat.getColor(mContext, R.color.mychart_k_line_boll_up), upsLabel);
                    LineDataSet mbDataSet = generateLineDataSet(bollEntrys.getMBs(), ContextCompat.getColor(mContext, R.color.mychart_k_line_boll_mid), "");
                    LineDataSet dnDataSet = generateLineDataSet(bollEntrys.getDNs(), ContextCompat.getColor(mContext, R.color.mychart_k_line_boll_down), dnsLabel);
                    lineData.addDataSet(upDataSet);
                    lineData.addDataSet(mbDataSet);
                    lineData.addDataSet(dnDataSet);
                    break;
                case HJGD:
                    combinedData.getCandleData().clearValues();
                    GoldTransitionEntry goldEntry = new GoldTransitionEntry(candleEntryList);
                    CandleData candleData = generateCandleDataDK(goldEntry.getTransformList());
                    combinedData.setData(candleData);

                    LineDataSet goldDataSet = generateLineDataSet(goldEntry.getLineList(),
                            ContextCompat.getColor(mContext, R.color.mychart_k_line_boll_down), dnsLabel);
                    lineData.addDataSet(goldDataSet);

                    ScatterDataSet set1 = new ScatterDataSet(goldEntry.getTransformK(), "");
                    set1.setShapeRenderer(new CustomScatterShapeRenderer("拐点"));
                    set1.setColor(Color.parseColor("#00000000"));
                    set1.setDrawValues(false);
                    set1.setScatterShapeSize(24f);

                    ScatterDataSet set2 = new ScatterDataSet(goldEntry.getTransformD(), "");
                    set2.setShapeRenderer(new CustomScatterShapeRenderer("拐点"));
                    set2.setColor(Color.parseColor("#00000000"));
                    set2.setDrawValues(false);
                    set2.setScatterShapeSize(24f);

//                    DKRadarEntrys dkRadarEntrys = new DKRadarEntrys(candleEntryList);
//
//                    combinedData.getCandleData().clearValues();
//                    CandleData candleData = generateCandleDataDK(dkRadarEntrys.getTransformList());
//                    combinedData.setData(candleData);
//
//                    ScatterDataSet set1 = new ScatterDataSet(dkRadarEntrys.getTransformK(), "");
//                    set1.setShapeRenderer(new CustomScatterShapeRenderer("拐点"));
//                    set1.setColor(Color.parseColor("#00000000"));
//                    set1.setDrawValues(false);
//                    set1.setScatterShapeSize(30f);
//
//                    ScatterDataSet set2 = new ScatterDataSet(dkRadarEntrys.getTransformD(), "");
//                    set2.setShapeRenderer(new CustomScatterShapeRenderer("哈哈哈"));
//                    set2.setColor(Color.parseColor("#00000000"));
//                    set2.setDrawValues(false);
//                    set2.setScatterShapeSize(24f);

                    scatterData.addDataSet(set1);
                    scatterData.addDataSet(set2);
                    scatterData.setHighlightEnabled(false);
                    combinedData.setData(scatterData);
                    break;
            }
            if (combinedData != null) {
                combinedData.setData(lineData);
                setData(combinedData);
                if (isReset) {
                    calculateScale();
                    moveViewToX(getXChartMax());
                } else {
                    invalidate();
                }
            }
        } else {
            clear();
        }
    }

    private void calculateScale() {
        setVisibleXRangeMinimum(MIN_VISIBLE_COUNT);
        Matrix save = new Matrix();
        save.setScale(getXRange() / xVisibleRange, 1f);
        mViewPortHandler.refresh(save, this, false);
        calculateOffsets();
        if (mChartTouchListener instanceof BarLineChartTouchListener) {
            ((BarLineChartTouchListener) mChartTouchListener).stopDeceleration();//停止滑动，防止计算出的scale被computeScroll()覆盖
        }
    }

    private CandleData generateCandleData(List<CandleEntry> candleEntryList) {
        CandleDataSet set = new CandleDataSet(candleEntryList, "");
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setShadowWidth(0.7f);
        set.setDecreasingColor(ContextCompat.getColor(mContext, R.color.mychart_fall_green));
        set.setDecreasingPaintStyle(Paint.Style.FILL);
        set.setIncreasingColor(ContextCompat.getColor(mContext, R.color.mychart_rose_red));
        set.setIncreasingPaintStyle(Paint.Style.STROKE);
        set.setNeutralColor(ContextCompat.getColor(mContext, R.color.mychart_text_gray));
        set.setShadowColorSameAsCandle(true);
        set.setHighlightLineWidth(0.5f);
        set.setHighLightColor(ContextCompat.getColor(mContext, R.color.mychart_high_light_line));
        set.setDrawValues(false);

        CandleData candleData = new CandleData();
        candleData.addDataSet(set);
        mCandleEntries.clear();
        mCandleEntries.addAll(candleEntryList);
        return candleData;
    }

    private CandleData generateCandleDataDK(List<CandleEntry> candleEntryList) {
        CandleDataSet set = new CandleDataSet(candleEntryList, "");
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setShadowWidth(0.7f);
        set.setDecreasingColor(ContextCompat.getColor(mContext, R.color.mychart_fall_green));
        set.setDecreasingPaintStyle(Paint.Style.STROKE);
        set.setIncreasingColor(ContextCompat.getColor(mContext, R.color.mychart_rose_red));
        set.setIncreasingPaintStyle(Paint.Style.STROKE);
        set.setNeutralColor(ContextCompat.getColor(mContext, R.color.mychart_text_gray));
        set.setShadowColorSameAsCandle(true);
        set.setHighlightLineWidth(0.5f);
        set.setHighLightColor(ContextCompat.getColor(mContext, R.color.mychart_high_light_line));
        set.setDrawValues(false);

        CandleData candleData = new CandleData();
        candleData.addDataSet(set);
        mCandleEntries.clear();
        mCandleEntries.addAll(candleEntryList);
        return candleData;
    }

    private LineDataSet generateLineDataSet(List<Entry> entries, int color, String label) {
        LineDataSet set = new LineDataSet(entries, label);
        set.setColor(color);
        set.setLineWidth(0.45f);
        set.setDrawCircles(false);
        set.setDrawCircleHole(false);
        set.setDrawValues(false);
        set.setHighlightEnabled(false);
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        return set;
    }

    @Override
    protected void drawMarkers(Canvas canvas) {
        super.drawMarkers(canvas);
        if (markerViewX == null || markerViewLeftY == null || markerViewRightY == null || !isDrawMarkersEnabled() || !valuesToHighlight()) {
            if (valueX < 0) {
                updateDataLabel(-1);
            }
            return;
        }
        Highlight highlight = mIndicesToHighlight[0];
        CandleDataSet set = (CandleDataSet) mData.getCandleData().getDataSetByIndex(0);
        Entry e = mData.getEntryForHighlight(highlight);
        int entryIndex = set.getEntryIndex(e);
        if (e == null || entryIndex > set.getEntryCount() * mAnimator.getPhaseX())
            return;
        float[] pos = getMarkerPosition(highlight);
        if (!mViewPortHandler.isInBounds(pos[0], pos[1]))
            return;

        markerViewX.refreshContent(e, highlight);
        markerViewLeftY.refreshContent(e, highlight);

        if (e instanceof CandleEntry) {
            CandleEntry entryFromX = getEntryFromX((CandleEntry) e);
            float beforeClose = ((CandleEntry) e).getClose();
            try {
                int x = candleEntryList.indexOf(entryFromX);
                if (null != highLightListener) {
                    highLightListener.onHighLightX(Math.round(entryFromX.getX()));
                }
                CandleEntry entry = candleEntryList.get(x - 1);
                beforeClose = entry.getClose();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            markerViewRightY.refreshContent(entryFromX, highlight, beforeClose);
            markerViewX.draw(canvas, pos[0], pos[1]);
            markerViewLeftY.draw(canvas, pos[0], pos[1]);
            markerViewRightY.draw(canvas, pos[0], pos[1]);
        }
    }

    private void updateDataLabel(int x) {
        try {
            int maxX = Math.round(getHighestVisibleX()) - 1;
            if (x > 0) {
                maxX = x;
            }
            //偏差值
            int offset;
            switch (currentType) {
                case SMA:
                    List<ILineDataSet> mSMADataSets = getLineData().getDataSets();
                    LineDataSet ma5DataSet = (LineDataSet) mSMADataSets.get(0);
                    LineDataSet ma10DataSet = (LineDataSet) mSMADataSets.get(1);
                    LineDataSet ma20DataSet = (LineDataSet) mSMADataSets.get(2);
                    MAEntrys maEntries = new MAEntrys(candleEntryList);
                    offset = 5;
                    setDataSetLabel(ma5DataSet, "SMA5=" + formatDouble(maEntries.getMA5s().get(maxX - offset > 0 ? maxX - offset : 0).getY()));
                    offset = 10;
                    setDataSetLabel(ma10DataSet, "SMA10=" + formatDouble(maEntries.getMA10s().get(maxX - offset > 0 ? maxX - offset : 0).getY()));
                    offset = 20;
                    setDataSetLabel(ma20DataSet, "SMA20=" + formatDouble(maEntries.getMA20s().get(maxX - offset > 0 ? maxX - offset : 0).getY()));
                    break;
                case EMA:
                    List<ILineDataSet> mEMADataSets = getLineData().getDataSets();
                    EMAEntrys emaEntries = new EMAEntrys(candleEntryList);
                    LineDataSet ema20DataSet = (LineDataSet) mEMADataSets.get(0);
                    setDataSetLabel(ema20DataSet, "EMA=" + formatDouble(emaEntries.getEMAs().get(maxX).getY()));
                    break;
                case BOLL:
                    offset = 20;
                    BOLLEntrys bollEntrys = new BOLLEntrys(candleEntryList);
                    List<ILineDataSet> mBollDataSets = getLineData().getDataSets();
                    LineDataSet upsDataSet = (LineDataSet) mBollDataSets.get(0);
                    LineDataSet mbsDataSet = (LineDataSet) mBollDataSets.get(1);
                    LineDataSet dnsDataSet = (LineDataSet) mBollDataSets.get(2);
                    setDataSetLabel(upsDataSet, "UP=" + formatDouble(bollEntrys.getUPs().get(maxX - offset > 0 ? maxX - offset : 0).getY()));
                    //setDataSetLabel(mbsDataSet,String.valueOf(bollEntrys.getMBs().get(maxX - offset - 1).getY()));
                    setDataSetLabel(dnsDataSet, "DN=" + formatDouble(bollEntrys.getDNs().get(maxX - offset > 0 ? maxX - offset : 0).getY()));
                    break;
            }
            notifyDataSetChanged();
        } catch (Exception e) {
            Log.e("KChart", "draw KChart Error... ");
        }
    }

    private CandleEntry getEntryFromX(CandleEntry candleEntry) {
        float x = candleEntry.getX();
        for (CandleEntry entry : candleEntryList) {
            if (x == entry.getX()) {
                return entry;
            }
        }
        return candleEntry;
    }

    public void setDataSetLabel(LineDataSet dataSet, String label) {
        dataSet.setLabel(label);
    }

    private HighLightListener highLightListener;

    public interface HighLightListener {

        void onHighLightX(int x);
    }

    public void setOnHighLightListener(HighLightListener listener) {
        this.highLightListener = listener;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        drawBgColor(canvas);
        super.onDraw(canvas);
    }

    private List<KTrainRect> bgList = new ArrayList<>();

    public void setBgColor(List<KTrainRect> arrayList) {
        bgList = arrayList;
    }

    private void drawBgColor(Canvas canvas) {
        if (!bgList.isEmpty()) {
            Paint paint = new Paint();
            for (KTrainRect r : bgList) {
                MPPointD xStart = this.getPixelForValues(r.startX, this.getYChartMax(), YAxis.AxisDependency.LEFT);
                MPPointD xStop = this.getPixelForValues(r.stopX, this.getYChartMin(), YAxis.AxisDependency.LEFT);
                paint.setColor(r.color);
                canvas.drawRect(new RectF((float) xStart.x, (float) xStart.y, (float) xStop.x, (float) xStop.y), paint);
            }
        }
    }

    @SuppressLint("DefaultLocale")
    public String formatDouble(double value) {
        return String.format("%.2f", value);
    }

    PointF downPoint = new PointF();

    public boolean onTouchEvent(MotionEvent evt) {
        switch (evt.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downPoint.x = evt.getX();
                downPoint.y = evt.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (getScaleX() > 1 && Math.abs(evt.getX() - downPoint.x) > 5) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                break;
        }
        return super.onTouchEvent(evt);
    }

}
